#coding=utf-8
import json
from basehandler import basehandler

__author__ = 'jy@cjlu.edu.cn'

from config import global_lookup
from SysCommon.tools import *
from models.s_user import bll_s_user
from models.v_ufs import bll_v_ufs
from web.utils import storage
from web.db import sqlwhere
import CODES

def processarg(i,fields=[]):
    """
    从输入中获取参数，如果参数不是空白或None则写入属性
    """
    rr=storage()
    if fields:
        for k in fields:
            if not (i.get(k,None) is None or i.get(k,"")==""):
                rr[k]=i[k]
    else:
        for k,v in i.items:
            if not(v is None or v==""):
                rr[k]=v
    return rr

def DataFilter(i):
    obj=bll_s_user()
    i.pageindex=i.get("pageindex",0)            #指定默认值
    i.pagesize=i.get("pagesize",18)             #指定默认值
    i=InitStorageBlank(i,["username","truename"])   #初始化属性，如果属性已经有则不去污染
    sqldic=processarg(i,["username","truename"])
    sqldic.userstatus='1'
    i.recs,i.rc,i.pc=obj.GetPagedRowsByDbWhere(i.pageindex,i.pagesize,where=sqlwhere(sqldic));
    return i

class Ajax(basehandler):
    def get(self):
        i=self.input()
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        if i.act=="ajax1":
            i=DataFilter(i)
            t=global_lookup.get_template("f00/T/TT/user_ajax1.html")
            self.write(t.render(i=i))

    def post(self):
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        i=self.input()
        obj=bll_s_user()
        if i.act=="stop":
            #停用
            if i.id:
                if obj.dostop(i.id):
                    return JsonResult("OK")
                else:
                    return JsonResult("NOOK")
            else:
                return JsonResult("NOOK")
        if i.act=="start":
            #停用
            if i.id:
                if obj.dostart(i.id):
                    return JsonResult("OK")
                else:
                    return JsonResult("NOOK")
            else:
                return JsonResult("NOOK")

        if i.act=="edit":
            if i.username and i.truename:
#                i.userpwd=getMD5(i.userpwd)
                obj.Save(i)
                self.write(json.dumps({"result":"OK"}))
        if i.act=="save":
            if i.username and i.truename and i.userpwd:
                i.userpwd=getMD5(i.userpwd)
                obj.Save(i)
                self.write(json.dumps({"result":"OK"}))
        if i.act=="del":
            if i.id:
                obj.DelRowById(i.id)
                self.write(json.dumps({"result":"OK"}))
        #恢复用户的默认密码，默认密码在codes中进行了配置
        #added by jy 2012-01-16
        if i.act=="restorepwd":
            if i.id:
                rec=obj.GetRowById(i.id)
                rec.userpwd=getMD5(CODES.CODES3)
                obj.SaveEx(rec,["id","userpwd"])
                self.write(toJson({"result":"OK"}))
        if i.act=="pwd":
            if i.pwd and (i.pwd1==i.pwd2):
                uobj=self.get_currentuser()
                if uobj.userpwd==getMD5(i.pwd):
                    uobj.userpwd=getMD5(i.pwd1)
                    obj.SaveEx(uobj,["id","userpwd"])
                    self.write(json.dumps({"result":"OK"}))
                else:
                    self.write(json.dumps({"result":"NOOK"}))
            else:
                    self.write(json.dumps({"result":"NOOK"}))
        #导出某个用户的权限明细added by jy 2012-02-01
        if i.act=="export1":
            from xlwt import Style
            i=self.input()
            from SysCommon.exceloperator import ExcelOperator
            excelobj=ExcelOperator()
            wb,ws=excelobj.openExistExcel(TP_PATH+"/static/T/userpower.xls")
            style = Style.default_style
            style.num_format_str="@"
            start_row=1
            #1.获取数据
            bjobj=bll_v_ufs()
            datas=bjobj.GetRowsByDbWhere(where="userid=$i",vars={"i":i.id},order="funno asc")
            #2.组合excel
            for d in datas:
                ws.write(start_row,0,d.userid)
                ws.write(start_row,1,d.username)
                ws.write(start_row,2,d.truename)
                ws.write(start_row,3,d.userpower)
                ws.write(start_row,4,d.funno)
                ws.write(start_row,5,d.funname)
                start_row+=1
                #3.输出excel
            nfilename="/static/tmpfiles/userpower_"+TimeStr()+".xls"
            wb.save(TP_PATH+nfilename)
            self.write(JsonResult(nfilename))
        #导出全部用户的已授权权限明细 added by jy 2012-02-02
        if i.act=="export":
            from xlwt import Style
            from SysCommon.exceloperator import ExcelOperator
            excelobj=ExcelOperator()
            wb,ws=excelobj.openExistExcel(TP_PATH+"/static/T/userpower.xls")
            style = Style.default_style
            style.num_format_str="@"
            start_row=1
            #1.获取数据
            bjobj=bll_v_ufs()
            datas=bjobj.GetRowsByDbWhere(order="funno asc")
            #2.组合excel
            for d in datas:
                ws.write(start_row,0,d.userid)
                ws.write(start_row,1,d.username)
                ws.write(start_row,2,d.truename)
                ws.write(start_row,3,d.userpower)
                ws.write(start_row,4,d.funno)
                ws.write(start_row,5,d.funname)
                start_row+=1
                #3.输出excel
            nfilename="/static/tmpfiles/userpower_"+TimeStr()+".xls"
            wb.save(TP_PATH+nfilename)
            self.write(JsonResult(nfilename))

class List(basehandler):
    #@checkpower("0022")
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        i.act=i.get('act','list')
        obj=bll_s_user()
        if i.act=="list":
            t=global_lookup.get_template("f00/T/user_list.html")
            i=DataFilter(i)

        if i.act=="add":
            t=global_lookup.get_template("f00/T/user_update.html")
            i.rec=storage()

        if i.act=="edit":
            t=global_lookup.get_template("f00/T/user_update.html")
            if i.id:
                i.rec=obj.GetRowById(i.id)
        self.write( t.render(i=i))

    #@checkpower("0022")
    def post(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        if i.act=="search":
            i=DataFilter(i)
            t=global_lookup.get_template("f00/T/user_list.html")
            self.write( t.render(i=i))

class Pwd(basehandler):
    def GET(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        if i.act=="pwd":
            t=global_lookup.get_template("f00/T/user_pwd.html")
            self.write( t.render())